<script lang="ts" setup>
import { ref } from 'vue'
import { debounce } from 'lodash-es'
import Conference from '@/api/modules/conference'
import Speech from '@/utils/speech'

const route = useRoute()
const speech = new Speech()

const notFoundMessage = ref('加载中...')

//状态控制
const isMeetingStarted = ref(false)
const startMeeting = () => {
  isMeetingStarted.value = true
}
const isRightHidden = ref(false)
const FloatClick = () => {
  if(isMeetingStarted.value==false) return;
  isRightHidden.value = !isRightHidden.value
}

// 滚动等待栏
const waitList = ref<HTMLDivElement | null>(null)
let lastTime = 0
let stopDuration = 0
let scrollDirection = 1
function scrollAnimation(now: number) {
  const delta = now - lastTime
  const offset = delta / 20
  lastTime = now
  if (waitList.value && waitList.value.scrollHeight > waitList.value.clientHeight + 23) {
    // 滚动到顶部或底部时停顿3秒
    if (waitList.value.scrollTop === 0 || waitList.value.scrollTop >= waitList.value.scrollHeight - waitList.value.clientHeight - 1) {
      stopDuration += delta
      if (stopDuration >= 3000) {
        scrollDirection = -scrollDirection
        waitList.value.scrollTop += delta * scrollDirection
        stopDuration = 0
      }
    }
    // 滚动中
    else {
      waitList.value.scrollTop += offset * scrollDirection
    }
  }
  requestAnimationFrame(scrollAnimation)
}

requestAnimationFrame(scrollAnimation)

const meeting = ref<MeetingApiTypes | null>(null)
// 当前进行中的会议信息
const currentSubject = ref<SubjectApiTypes.subjectItem | null>(null)
// 已完成的议题列表
const completedSubjectList = ref<SubjectApiTypes.subjectItem[]>([])
// 等待呼叫的议题列表
const waitingSubjectList = ref<SubjectApiTypes.subjectItem[]>([])

// 临时新增人员
const tempAddPerson = ref<SubjectApiTypes.Person[]>([])

// 筛选并更新议题列表
function updateSubjectList(clearTempAddPerson = true) {
  if (!meeting.value) {
    return
  }

  // 根据议题状态筛选
  completedSubjectList.value = meeting.value.subjectList.filter(subject => subject.status === 2)
  waitingSubjectList.value = meeting.value.subjectList.filter(subject => subject.status === 0)
  // 议题只取前三个
  waitingSubjectList.value = waitingSubjectList.value.slice(0, 3)
  const currentSubjectIndex = meeting.value.subjectList.findIndex(subject => subject.status === 1)
  if (currentSubjectIndex !== -1) {
    currentSubject.value = meeting.value.subjectList[currentSubjectIndex]
  }
  else {
    currentSubject.value = null
  }

  if (clearTempAddPerson) {
    tempAddPerson.value = []
  }
}
updateSubjectList()

const repullMeeting = debounce(() => {
  Conference.getDetail(route.params.id as string).then((res) => {
    meeting.value = res.data
    updateSubjectList()
  })
}, 1000)

// websocket连接
const BASEURL = import.meta.env.VITE_APP_WS_BASEURL
let websocket: WebSocket | null = null
onMounted(() => {
  websocket = new WebSocket(`${BASEURL}${route.params.id}`)
  websocket.onmessage = (event) => {
    const msg = JSON.parse(event.data)
    if (msg.type === 'repullMeeting') { // 重新拉取会议信息
      repullMeeting()
    }
    else if (msg.type === 'addTempPersons') { // 临时新增人员
      const subjectId = msg.data.subjectId// 议题id
      const tempPersons = msg.data.tempPersons// 临时新增人员列表
      const subject = meeting.value?.subjectList.find(subject => subject.id === subjectId)
      if (subject) { // 会议中存在该议题
        subject.personList.push(...tempPersons)
      }
      if (currentSubject.value?.id === subjectId) { // 如果是当前进行中的议题，则新增人员还需显示到新增列席处
        tempAddPerson.value.push(...tempPersons)
        // 播报人员信息
        let personMsg = '请'
        for (const person of tempPersons) {
          personMsg += `${person.name}，`
        }
        personMsg += '马上参会'
        speech.speak(personMsg)
      }
    }
    else if (msg.type === 'noSuchMeeting') { // 会议不存在
      meeting.value = null
    }
    else if (msg.type === 'meetingInfo') { // 会议信息
      meeting.value = msg.data
      updateSubjectList()
      // speech.speak('语音测试')
    }
    else if (msg.type === 'updateSubjectStatus') { // 开始议题
      const { subjectId, status } = msg.data
      const subject = meeting.value?.subjectList.find(subject => subject.id === subjectId)
      if (subject) {
        subject.status = status
      }
      updateSubjectList()
      if (status === 1) {
        // 播报议题信息
        const index = meeting.value?.subjectList.findIndex(subject => subject.id === subjectId)
        if (index === -1) {
          console.error('议题不存在')
        }
        speech.speak(`请第${index! + 1}项议题的相关人员参会`)
      }
    }
    else if (msg.type === 'addSubject') { // 新增议题
      const subject = msg.data
      meeting.value?.subjectList.push(subject)
      updateSubjectList(false)
    }
    else if (msg.type === 'removeSubject') { // 移除议题
      const subjectId = msg.data
      const subjectIndex = meeting.value?.subjectList.findIndex(subject => subject.id === subjectId)
      if (subjectIndex !== undefined && subjectIndex !== -1) {
        meeting.value?.subjectList.splice(subjectIndex, 1)
      }
      updateSubjectList(false)
    }

    notFoundMessage.value = '找不到该会议信息'
  }
})
onUnmounted(() => {
  websocket?.close()
})
</script>

<template>
  <div class="sub-conference">
    <WebRTCFloatingWindow @click="FloatClick"/>
    <div v-if="meeting">
      <header>
        <h2 class="title">
          {{ meeting.name }}
        </h2>
      </header>
      <div class="content">
        <div class="left-filed" :class="{ 'meeting-started': isMeetingStarted, 'meeting-hidden': isRightHidden}">
          <img v-if="!isMeetingStarted" src="../../assets/images/background.png">
          <el-button
            type="primary"
            class="start-meeting-btn"
            @click="startMeeting"
            v-if="!isMeetingStarted"
          >
            开始会议
          </el-button>
          <WebRTCService class="meet-filed" v-if="isMeetingStarted" />
        </div>
        <div class="right" :class="{ 'meeting-started': isMeetingStarted,'meeting-hidden': isRightHidden}">
          <h3><img src="../../assets/images/shijianchuo.png">
            <span v-if="isMeetingStarted">会议进行中</span>
            <span v-else>会议未开始</span>
          </h3>
          <div v-if="currentSubject" class="nowmeeting-name">
            <div class="marquee-container">
              <div class="marquee">
                {{ currentSubject?.name }}
              </div>
            </div>
          </div>
          <div v-else class="nowmeeting-name">
            <span v-if="isMeetingStarted">暂无正在进行议题</span>
            <span v-else>请等待主持人开始会议</span>
          </div>
          <p>列席人员：</p>
          <div v-if="!currentSubject?.personList" class="personname">
            无
          </div>
          <div v-for="(person, index) in currentSubject?.personList" :key="person.id" class="personname">
            {{ person.name }}老师
            <span v-if="currentSubject && index < currentSubject?.personList.length - 1">、</span>
          </div>
          <h4><img src="../../assets/images/shijianzhouqi.png" alt="">等待呼叫</h4>
          <div v-for="subject in waitingSubjectList" :key="subject.id" class="wating">
            <div class="marquee-container">
              <div class="marquee">
                等待中&#45;&#45;{{ subject.name }}
              </div>
            </div>
          </div>
          <h4><img src="../../assets/images/user.png" alt="">新增列席</h4>
          <div v-for="person in tempAddPerson" :key="person.id" class="wating">
            列席人员：{{ `${person.name} ` }}
          </div>
        </div>
      </div>
    </div>
    <div v-else class="text-notfound">
      {{ notFoundMessage }}
    </div>
  </div>
</template>

<style lang="scss" scoped>
.sub-conference {
  height: 100%;
  width: 100%;
}

.title {
  height: 8vh;
  font-size: 35px;
  color: white;
  font-weight: 400;
  background: #3d84ff;
}

.content {
  display: flex;
  transition: all 0.3s ease;
}

.left-filed {
  flex: 0 0 50%;
  width: 50%;
  height: 875px;
  position: relative;
  transition: all 0.3s ease;// 添加过渡效果

  img {
    width: 100%;
    height: 100%;
  }

  .meet-filed {
    width: 100%;
    height: 100%;
  }

  &.meeting-started {
    flex: 0 0 80%; // 会议开始后扩大左侧宽度
  }
  &.meeting-hidden {
    flex: 0 0 100%; //扩大
  }

  .start-meeting-btn {
    position: absolute;
    bottom: 20px;
    left: 50%;
    transform: translateX(-50%);
    width: 80%;
    height: 40px;
    font-size: 16px;
  }
}

.right {
  flex: 0 0 50%;
  width: 50%;
  height: 100%;
  background-color: #f6f9fe;
  text-align: center;
  transition: all 0.3s ease;

  &.meeting-started {
    flex: 0 0 20%; // 会议开始后缩小右侧宽度
  }
  &.meeting-hidden {
    flex: 0 0 0%; //隐藏
  }


  /* 原有右侧样式保持不变 */
  img {
    width: 25px;
    height: 25px;
    margin-right: 5px;
    margin-top: -2px;
    vertical-align: middle;
  }

  h3 {
    color: rgb(63 143 231);
    height: 50px;
    line-height: 50px;
    margin: 10px;
  }

  .nowmeeting-name {
    padding: 0 10px;
    background-color: #3b87ff;
    min-height: 50px;
    line-height: 50px;
    color: #fff;

    .marquee-container {
      white-space: nowrap;
      overflow: hidden;
    }
  }

  p {
    display: inline;
    height: 50px;
    line-height: 50px;
    color: #0d0f10;
    font-weight: 700;
  }

  .personname {
    display: inline;
    line-height: 35px;
    color: #d22933;
  }

  h4 {
    margin: 0;
    height: 50px;
    line-height: 50px;
    color: #0d0f10;
    background-color: #fff;
  }

  .wating {
    padding: 0 10px;
    min-height: 50px;
    line-height: 50px;
    color: #707173;
    background-color: #eff8ff;

    .marquee-container {
      white-space: nowrap;
      overflow: hidden;
    }
  }

  .wating:nth-child(2n) {
    background-color: #fff;
  }
}

.border {
  border: 1px solid black;
}

.border-top {
  border-top: 1px solid black;
}

.border-left {
  border-left: 1px solid black;
}

.border-bottom {
  border-bottom: 1px solid black;
}

.border-right {
  border-right: 1px solid black;
}

.scroll-text {
  font-size: 30px;
  color: red;
}

header {
  text-align: center;

  h2 {
    font-size: 40px;
    color: red;
    font-weight: 400;
    margin: 0;
    padding: 20px 0;
  }
}

.container {
  width: 80%;
  height: 100%;
  margin: 0 auto;


  .meeting-name {
    font-size: 20px;
    padding: 14px;
  }

  main {
    display: flex;

    h3 {
      text-align: center;
      background-color: #00b0f0;
      margin: 0;
      padding: 20px 0;
      font-size: 21px;
    }

    .left {
      flex-basis: 40%;
      width: 40%;

      .person-list {
        padding: 20px;
        display: flex;
        flex-wrap: wrap;
        gap: 20px;

        .item {
          font-size: 18px;
        }
      }
    }

    .right {
      flex-basis: 60%;
      width: 60%;

      .wait-list {
        height: 329px;

        /* 6个议题的高度 - 1px */
        overflow: hidden;

        .item {
          border-bottom: 1px solid black;
        }

        .bottom-gap {
          height: 20px;
          line-height: 20px;
          font-size: 12px;
          color: #aaa;
          text-align: center;
        }
      }
    }
  }

  footer {
    display: flex;
    height: 100px;

    .left {
      padding: 0 20px;
      width: 200px;
      font-size: 18px;
      display: flex;
      align-items: center;
    }

    .content {
      padding: 20px;
      font-size: 18px;
    }
  }
}

.text-notfound {
  text-align: center;
  color: red;
  font-size: 40px;
}
</style>
